

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="c5p1ng">
  <meta name="keywords" content="">
  
    <meta name="description" content="HashMap和Hashtable的区别 两者最主要的区别在于Hashtable是线程安全，而HashMap则非线程安全。Hashtable的实现方法里面都添加了synchronized关键字来确保线程同步，因此相对而言HashMap性能会高一些，我们平时使用时若无特殊需求建议使用HashMap，在多线程环境下若使用HashMap需要使用Collections.synchronizedMap()方">
<meta property="og:type" content="article">
<meta property="og:title" content="HashMap源码分析（基于jdk7）">
<meta property="og:url" content="http://example.com/2023/06/11/HashMap%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E5%9F%BA%E4%BA%8Ejdk7%EF%BC%89/index.html">
<meta property="og:site_name" content="c5p1ng个人博客">
<meta property="og:description" content="HashMap和Hashtable的区别 两者最主要的区别在于Hashtable是线程安全，而HashMap则非线程安全。Hashtable的实现方法里面都添加了synchronized关键字来确保线程同步，因此相对而言HashMap性能会高一些，我们平时使用时若无特殊需求建议使用HashMap，在多线程环境下若使用HashMap需要使用Collections.synchronizedMap()方">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-06-11T03:25:33.000Z">
<meta property="article:modified_time" content="2023-06-11T06:20:55.553Z">
<meta property="article:author" content="c5p1ng">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>HashMap源码分析（基于jdk7） - c5p1ng个人博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="HashMap源码分析（基于jdk7）"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-06-11 11:25" pubdate>
          2023年6月11日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          91 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">HashMap源码分析（基于jdk7）</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="HashMap和Hashtable的区别"><a href="#HashMap和Hashtable的区别" class="headerlink" title="HashMap和Hashtable的区别"></a>HashMap和Hashtable的区别</h1><ul>
<li><p>两者最主要的区别在于Hashtable是线程安全，而HashMap则非线程安全。Hashtable的实现方法里面都添加了synchronized关键字来确保线程同步，因此相对而言HashMap性能会高一些，我们平时使用时若无特殊需求建议使用HashMap，在多线程环境下若使用HashMap需要使用Collections.synchronizedMap()方法来获取一个线程安全的集合（Collections.synchronizedMap()实现原理是Collections定义了一个SynchronizedMap的内部类，这个类实现了Map接口，在调用方法时使用synchronized来保证线程同步,当然了实际上操作的还是我们传入的HashMap实例，简单的说就是Collections.synchronizedMap()方法帮我们在操作HashMap时自动添加了synchronized来实现线程同步，类似的其它Collections.synchronizedXX方法也是类似原理）</p>
</li>
<li><p>HashMap可以使用null作为key，而Hashtable则不允许null作为key；虽说HashMap支持null值作为key，不过建议还是尽量避免这样使用，因为一旦不小心使用了，若因此引发一些问题，排查起来很是费事；HashMap以null作为key时，总是存储在table数组的第一个节点上</p>
</li>
<li><p>HashMap是对Map接口的实现，HashTable实现了Map接口和Dictionary抽象类</p>
</li>
<li><p>HashMap的初始容量为16，Hashtable初始容量为11，两者的填充因子默认都是0.75；HashMap扩容时是当前容量翻倍即:capacity<em>2，Hashtable扩容时是容量翻倍+1即:capacity</em>2+1</p>
</li>
<li><p>两者计算hash的方法不同。</p>
<p>Hashtable计算hash是直接使用key的hashcode对table数组的长度直接进行取模：</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">int</span> <span class="hljs-variable">hash</span> <span class="hljs-operator">=</span> key.hashCode();<br><span class="hljs-type">int</span> <span class="hljs-variable">index</span> <span class="hljs-operator">=</span> (hash &amp; <span class="hljs-number">0x7FFFFFFF</span>) % tab.length;<br></code></pre></td></tr></table></figure>

<p>​		HashMap计算hash对key的hashcode进行了二次hash，以获得更好的散列值，然后对table数组长度取摸：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">static</span> <span class="hljs-type">int</span> <span class="hljs-title function_">hash</span><span class="hljs-params">(<span class="hljs-type">int</span> h)</span> &#123;<br>  <span class="hljs-comment">// This function ensures that hashCodes that differ only by</span><br>  <span class="hljs-comment">// constant multiples at each bit position have a bounded</span><br>  <span class="hljs-comment">// number of collisions (approximately 8 at default load factor).</span><br>  h ^= (h &gt;&gt;&gt; <span class="hljs-number">20</span>) ^ (h &gt;&gt;&gt; <span class="hljs-number">12</span>);<br>  <span class="hljs-keyword">return</span> h ^ (h &gt;&gt;&gt; <span class="hljs-number">7</span>) ^ (h &gt;&gt;&gt; <span class="hljs-number">4</span>);<br>  &#125;<br><br><span class="hljs-keyword">static</span> <span class="hljs-type">int</span> <span class="hljs-title function_">indexFor</span><span class="hljs-params">(<span class="hljs-type">int</span> h, <span class="hljs-type">int</span> length)</span> &#123;<br>  <span class="hljs-keyword">return</span> h &amp; (length-<span class="hljs-number">1</span>);<br>  &#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>HashMap和Hashtable的底层实现都是数组+链表结构实现</li>
</ul>
<h1 id="HashMap和Hashtable的实现原理"><a href="#HashMap和Hashtable的实现原理" class="headerlink" title="HashMap和Hashtable的实现原理"></a>HashMap和Hashtable的实现原理</h1><p>HashMap和Hashtable的底层实现都是数组+链表结构实现的，这点上完全一致</p>
<p>添加、删除、获取元素时都是先计算hash，根据hash和table.length计算index也就是table数组的下标，然后进行相应操作，下面以HashMap为例说明下它的简单实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * HashMap的默认初始容量 必须为2的n次幂</span><br><span class="hljs-comment">    */</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">DEFAULT_INITIAL_CAPACITY</span> <span class="hljs-operator">=</span> <span class="hljs-number">16</span>;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * HashMap的最大容量，可以认为是int的最大值   </span><br><span class="hljs-comment">    */</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">MAXIMUM_CAPACITY</span> <span class="hljs-operator">=</span> <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">30</span>;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 默认的加载因子</span><br><span class="hljs-comment">    */</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">float</span> <span class="hljs-variable">DEFAULT_LOAD_FACTOR</span> <span class="hljs-operator">=</span> <span class="hljs-number">0.75f</span>;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * HashMap用来存储数据的数组</span><br><span class="hljs-comment">    */</span><br>    <span class="hljs-keyword">transient</span> Entry[] table;<br><br></code></pre></td></tr></table></figure>

<h2 id="1、HashMap的创建"><a href="#1、HashMap的创建" class="headerlink" title="1、HashMap的创建"></a>1、HashMap的创建</h2><p>HashMap默认初始化时会创建一个默认容量为16的Entry数组，默认加载因子为0.75，同时设置临界值为16*0.75</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * Constructs an empty &lt;tt&gt;HashMap&lt;/tt&gt; with the default initial capacity</span><br><span class="hljs-comment">    * (16) and the default load factor (0.75).</span><br><span class="hljs-comment">    */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">HashMap</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-built_in">this</span>.loadFactor = DEFAULT_LOAD_FACTOR;<br>        threshold = (<span class="hljs-type">int</span>)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);<br>        table = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Entry</span>[DEFAULT_INITIAL_CAPACITY];<br>        init();<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="2、put方法"><a href="#2、put方法" class="headerlink" title="2、put方法"></a>2、put方法</h2><p>HashMap会对null值key进行特殊处理，总是放到table[0]位置；put过程是先计算hash然后通过hash与table.length取摸计算index值，然后将key放到table[index]位置，当table[index]已存在其它元素时，会在table[index]位置形成一个链表，将新添加的元素放在table[index]，原来的元素通过Entry的next进行链接，这样以链表形式解决hash冲突问题，当元素数量达到临界值(capactiy<em>factor)时，则进行扩容，是table数组长度变为table.length</em>2</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> V <span class="hljs-title function_">put</span><span class="hljs-params">(K key, V value)</span> &#123;<br>        <span class="hljs-keyword">if</span> (key == <span class="hljs-literal">null</span>)<br>            <span class="hljs-keyword">return</span> putForNullKey(value); <span class="hljs-comment">//处理null值</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">hash</span> <span class="hljs-operator">=</span> hash(key.hashCode());<span class="hljs-comment">//计算hash</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> indexFor(hash, table.length);<span class="hljs-comment">//计算在数组中的存储位置</span><br>    <span class="hljs-comment">//遍历table[i]位置的链表，查找相同的key，若找到则使用新的value替换掉原来的oldValue并返回oldValue</span><br>        <span class="hljs-keyword">for</span> (Entry&lt;K,V&gt; e = table[i]; e != <span class="hljs-literal">null</span>; e = e.next) &#123;<br>            Object k;<br>            <span class="hljs-keyword">if</span> (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k))) &#123;<br>                <span class="hljs-type">V</span> <span class="hljs-variable">oldValue</span> <span class="hljs-operator">=</span> e.value;<br>                e.value = value;<br>                e.recordAccess(<span class="hljs-built_in">this</span>);<br>                <span class="hljs-keyword">return</span> oldValue;<br>            &#125;<br>        &#125;<br>    <span class="hljs-comment">//若没有在table[i]位置找到相同的key，则添加key到table[i]位置，新的元素总是在table[i]位置的第一个元素，原来的元素后移</span><br>        modCount++;<br>        addEntry(hash, key, value, i);<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br><br> <br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">addEntry</span><span class="hljs-params">(<span class="hljs-type">int</span> hash, K key, V value, <span class="hljs-type">int</span> bucketIndex)</span> &#123;<br>    <span class="hljs-comment">//添加key到table[bucketIndex]位置，新的元素总是在table[bucketIndex]的第一个元素，原来的元素后移</span><br>    Entry&lt;K,V&gt; e = table[bucketIndex];<br>        table[bucketIndex] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Entry</span>&lt;K,V&gt;(hash, key, value, e);<br>    <span class="hljs-comment">//判断元素个数是否达到了临界值，若已达到临界值则扩容，table长度翻倍</span><br>        <span class="hljs-keyword">if</span> (size++ &gt;= threshold)<br>            resize(<span class="hljs-number">2</span> * table.length);<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="3、get方法"><a href="#3、get方法" class="headerlink" title="3、get方法"></a>3、get方法</h2><p>同样当key为null时会进行特殊处理，在table[0]的链表上查找key为null的元素；get的过程是先计算hash然后通过hash与table.length取摸计算index值，然后遍历table[index]上的链表，直到找到key，然后返回</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> V <span class="hljs-title function_">get</span><span class="hljs-params">(Object key)</span> &#123;<br>        <span class="hljs-keyword">if</span> (key == <span class="hljs-literal">null</span>)<br>            <span class="hljs-keyword">return</span> getForNullKey();<span class="hljs-comment">//处理null值</span><br>        <span class="hljs-type">int</span> <span class="hljs-variable">hash</span> <span class="hljs-operator">=</span> hash(key.hashCode());<span class="hljs-comment">//计算hash</span><br>    <span class="hljs-comment">//在table[index]遍历查找key，若找到则返回value，找不到返回null</span><br>        <span class="hljs-keyword">for</span> (Entry&lt;K,V&gt; e = table[indexFor(hash, table.length)];<br>            e != <span class="hljs-literal">null</span>;<br>            e = e.next) &#123;<br>            Object k;<br>            <span class="hljs-keyword">if</span> (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k)))<br>                <span class="hljs-keyword">return</span> e.value;<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="4、remove方法"><a href="#4、remove方法" class="headerlink" title="4、remove方法"></a>4、remove方法</h2><p>remove方法和put get类似，计算hash，计算index，然后遍历查找，将找到的元素从table[index]链表移除</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> V <span class="hljs-title function_">remove</span><span class="hljs-params">(Object key)</span> &#123;<br>        Entry&lt;K,V&gt; e = removeEntryForKey(key);<br>        <span class="hljs-keyword">return</span> (e == <span class="hljs-literal">null</span> ? <span class="hljs-literal">null</span> : e.value);<br>    &#125;<br>    <span class="hljs-keyword">final</span> Entry&lt;K,V&gt; <span class="hljs-title function_">removeEntryForKey</span><span class="hljs-params">(Object key)</span> &#123;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">hash</span> <span class="hljs-operator">=</span> (key == <span class="hljs-literal">null</span>) ? <span class="hljs-number">0</span> : hash(key.hashCode());<br>        <span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> indexFor(hash, table.length);<br>        Entry&lt;K,V&gt; prev = table[i];<br>        Entry&lt;K,V&gt; e = prev;<br><br>        <span class="hljs-keyword">while</span> (e != <span class="hljs-literal">null</span>) &#123;<br>            Entry&lt;K,V&gt; next = e.next;<br>            Object k;<br>            <span class="hljs-keyword">if</span> (e.hash == hash &amp;&amp; ((k = e.key) == key || (key != <span class="hljs-literal">null</span> &amp;&amp; key.equals(k)))) &#123;<br>                modCount++;<br>                size--;<br>                <span class="hljs-keyword">if</span> (prev == e)<br>                    table[i] = next;<br>                <span class="hljs-keyword">else</span><br>                    prev.next = next;<br>                e.recordRemoval(<span class="hljs-built_in">this</span>);<br>                <span class="hljs-keyword">return</span> e;<br>            &#125;<br>            prev = e;<br>            e = next;<br>        &#125;<br><br>        <span class="hljs-keyword">return</span> e;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="5、resize方法"><a href="#5、resize方法" class="headerlink" title="5、resize方法"></a>5、resize方法</h2><p>resize方法在hashmap中并没有公开，这个方法实现了非常重要的hashmap扩容，具体过程为：先创建一个容量为table.length<em>2的新table，修改临界值，然后把table里面元素计算hash值并使用hash与table.length</em>2重新计算index放入到新的table里面</p>
<p>这里需要注意下是用每个元素的hash全部重新计算index，而不是简单的把原table对应index位置元素简单的移动到新table对应位置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">void</span> <span class="hljs-title function_">resize</span><span class="hljs-params">(<span class="hljs-type">int</span> newCapacity)</span> &#123;<br>        Entry[] oldTable = table;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">oldCapacity</span> <span class="hljs-operator">=</span> oldTable.length;<br>        <span class="hljs-keyword">if</span> (oldCapacity == MAXIMUM_CAPACITY) &#123;<br>            threshold = Integer.MAX_VALUE;<br>            <span class="hljs-keyword">return</span>;<br>        &#125;<br><br>        Entry[] newTable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Entry</span>[newCapacity];<br>        transfer(newTable);<br>        table = newTable;<br>        threshold = (<span class="hljs-type">int</span>)(newCapacity * loadFactor);<br>    &#125;<br><br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">transfer</span><span class="hljs-params">(Entry[] newTable)</span> &#123;<br>        Entry[] src = table;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">newCapacity</span> <span class="hljs-operator">=</span> newTable.length;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">j</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; j &lt; src.length; j++) &#123;<br>            Entry&lt;K,V&gt; e = src[j];<br>            <span class="hljs-keyword">if</span> (e != <span class="hljs-literal">null</span>) &#123;<br>                src[j] = <span class="hljs-literal">null</span>;       <br>                <span class="hljs-keyword">do</span> &#123;<br>                    Entry&lt;K,V&gt; next = e.next;<br>                    <span class="hljs-comment">//重新对每个元素计算index int i = indexFor(e.hash, newCapacity);</span><br>                    e.next = newTable[i];<br>                    newTable[i] = e;<br>                    e = next;<br>                &#125; <span class="hljs-keyword">while</span> (e != <span class="hljs-literal">null</span>);<br>            &#125;<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="6、clear方法"><a href="#6、clear方法" class="headerlink" title="6、clear方法"></a>6、clear方法</h2><p>clear方法非常简单，就是遍历table然后把每个位置置为null，同时修改元素个数为0</p>
<p>需要注意的是clear方法只会清楚里面的元素，并不会重置capactiy</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">clear</span><span class="hljs-params">()</span> &#123;<br>        modCount++;<br>        Entry[] tab = table;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; tab.length; i++)<br>            tab[i] = <span class="hljs-literal">null</span>;<br>        size = <span class="hljs-number">0</span>;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h2 id="7、containsKey和containsValue"><a href="#7、containsKey和containsValue" class="headerlink" title="7、containsKey和containsValue"></a>7、containsKey和containsValue</h2><p>containsKey方法是先计算hash然后使用hash和table.length取摸得到index值，遍历table[index]元素查找是否包含key相同的值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">containsKey</span><span class="hljs-params">(Object key)</span> &#123;<br>        <span class="hljs-keyword">return</span> getEntry(key) != <span class="hljs-literal">null</span>;<br>    &#125;<br><span class="hljs-keyword">final</span> Entry&lt;K,V&gt; <span class="hljs-title function_">getEntry</span><span class="hljs-params">(Object key)</span> &#123;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">hash</span> <span class="hljs-operator">=</span> (key == <span class="hljs-literal">null</span>) ? <span class="hljs-number">0</span> : hash(key.hashCode());<br>        <span class="hljs-keyword">for</span> (Entry&lt;K,V&gt; e = table[indexFor(hash, table.length)];<br>            e != <span class="hljs-literal">null</span>;<br>            e = e.next) &#123;<br>            Object k;<br>            <span class="hljs-keyword">if</span> (e.hash == hash &amp;&amp;<br>                ((k = e.key) == key || (key != <span class="hljs-literal">null</span> &amp;&amp; key.equals(k))))<br>                <span class="hljs-keyword">return</span> e;<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br></code></pre></td></tr></table></figure>

<p>containsValue方法就比较粗暴了，就是直接遍历所有元素直到找到value，由此可见HashMap的containsValue方法本质上和普通数组和list的contains方法没什么区别，你别指望它会像containsKey那么高效</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">containsValue</span><span class="hljs-params">(Object value)</span> &#123;<br>    <span class="hljs-keyword">if</span> (value == <span class="hljs-literal">null</span>)<br>            <span class="hljs-keyword">return</span> containsNullValue();<br><br>    Entry[] tab = table;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; tab.length ; i++)<br>            <span class="hljs-keyword">for</span> (<span class="hljs-type">Entry</span> <span class="hljs-variable">e</span> <span class="hljs-operator">=</span> tab[i] ; e != <span class="hljs-literal">null</span> ; e = e.next)<br>                <span class="hljs-keyword">if</span> (value.equals(e.value))<br>                    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h1 id="HashMap的简化实现MyHashMap"><a href="#HashMap的简化实现MyHashMap" class="headerlink" title="HashMap的简化实现MyHashMap"></a>HashMap的简化实现MyHashMap</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.c5p1ng;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">QuickHashMap</span> &#123;<br>     <span class="hljs-comment">//初始化大小16</span><br>     <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">DEFAULT_INTIAL_CAPACITY</span> <span class="hljs-operator">=</span> <span class="hljs-number">16</span>;<br>     <span class="hljs-comment">//默认负载因子0.75</span><br>     <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">float</span> <span class="hljs-variable">DEFAULT_LOAD_FACTOR</span> <span class="hljs-operator">=</span> <span class="hljs-number">0.75f</span>;<br>     <span class="hljs-comment">//临界值</span><br>     <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> threshold;<br>     <span class="hljs-comment">//元素个数</span><br>     <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> size;<br>     <span class="hljs-comment">//扩容次数</span><br>     <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> resize;<br><br>     <span class="hljs-keyword">private</span> HashEntry[] table;<br><br>     <span class="hljs-keyword">public</span> <span class="hljs-title function_">QuickHashMap</span><span class="hljs-params">()</span> &#123;<br>           table = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashEntry</span>[DEFAULT_INTIAL_CAPACITY];<br>           threshold = (<span class="hljs-type">int</span>) (DEFAULT_INTIAL_CAPACITY * DEFAULT_LOAD_FACTOR);<br>           size = <span class="hljs-number">0</span>;<br>     &#125;<br><br>     <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> <span class="hljs-title function_">index</span><span class="hljs-params">(Object key)</span> &#123;<br>           <span class="hljs-keyword">return</span> key.hashCode() % table.length;<br>     &#125;<br><br>     <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * 添加数据</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@param</span> key</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@param</span> value</span><br><span class="hljs-comment">      */</span><br>     <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">put</span><span class="hljs-params">(Object key, Object value)</span> &#123;<br>           <span class="hljs-keyword">if</span>(key == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span>;<br>           <span class="hljs-type">int</span> <span class="hljs-variable">index</span> <span class="hljs-operator">=</span> index(key);<br>           <span class="hljs-comment">//遍历index位置的entry，若找到重复key则更新对应entry值，然后返回</span><br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">entry</span> <span class="hljs-operator">=</span> table[index];<br>           <span class="hljs-keyword">while</span>(entry != <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-keyword">if</span> (entry.getKey().hashCode() == key.hashCode() &amp;&amp; (entry.getKey() == key || entry.getKey().equals(key))) &#123;<br>                   entry.setValue(value);<br>                   <span class="hljs-keyword">return</span>;<br>                &#125;<br>                entry = entry.getNext();<br>           &#125;<br>           <span class="hljs-comment">//若没重复key，则新增</span><br>           add(index, key, value);<br>     &#125;<br><br>     <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">add</span><span class="hljs-params">(<span class="hljs-type">int</span> index, Object key, Object value)</span> &#123;<br>           <span class="hljs-comment">//将新的e放到table的index位置第一个，若原来有值则以链表形式存放</span><br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">e</span> <span class="hljs-operator">=</span> table[index];<br>           table[index] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashEntry</span>(key, value, e); <span class="hljs-comment">//参数e, 是HashEntry.next</span><br>           <span class="hljs-comment">//判断size是否到达临界值</span><br>           <span class="hljs-keyword">if</span>(size++ &gt;= threshold) &#123;<br>                resize(table.length*<span class="hljs-number">2</span>);<br>           &#125;<br>     &#125;<br><br>     <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">resize</span><span class="hljs-params">(<span class="hljs-type">int</span> capacity)</span> &#123;<br>           <span class="hljs-keyword">if</span>(capacity &lt;= table.length) <span class="hljs-keyword">return</span>;<br>           HashEntry[] newTable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashEntry</span>[capacity];<br>        <span class="hljs-comment">//遍历原table，将每个entry都重新计算hash放入newTable中 3,2,1</span><br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; table.length; i++) &#123;<br>            <span class="hljs-type">HashEntry</span> <span class="hljs-variable">old</span> <span class="hljs-operator">=</span> table[i];<br>            <span class="hljs-keyword">while</span> (old != <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-type">HashEntry</span> <span class="hljs-variable">next</span> <span class="hljs-operator">=</span> old.getNext();<br>                <span class="hljs-type">int</span> <span class="hljs-variable">index</span> <span class="hljs-operator">=</span> index(old.getKey());<br>                old.setNext(newTable[index]);<br>                newTable[index] = old;<br>                old = next;<br>            &#125;<br>        &#125;<br>        <span class="hljs-comment">//用newTable替table</span><br>        table = newTable;<br>        <span class="hljs-comment">//修改临界值</span><br>        threshold = (<span class="hljs-type">int</span>) (table.length * DEFAULT_LOAD_FACTOR);<br>        resize++;<br>     &#125;<br><br>     <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * 获取key对应的值</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@param</span> key</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">      */</span><br>     <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">get</span><span class="hljs-params">(Object key)</span> &#123;<br>           <span class="hljs-keyword">if</span>(key == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">entry</span> <span class="hljs-operator">=</span> getEntry(key);<br>           <span class="hljs-keyword">return</span> entry == <span class="hljs-literal">null</span> ? <span class="hljs-literal">null</span> : entry.getValue();<br>     &#125;<br><br>     <span class="hljs-keyword">public</span> HashEntry <span class="hljs-title function_">getEntry</span><span class="hljs-params">(Object key)</span> &#123;<br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">entry</span> <span class="hljs-operator">=</span> table[index(key)];<br>           <span class="hljs-keyword">while</span>(entry != <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-keyword">if</span>(entry.getKey().hashCode() == key.hashCode() &amp;&amp; (entry.getKey() == key || entry.getKey().equals(key))) &#123;<br>                     <span class="hljs-keyword">return</span> entry;<br>                &#125;<br>                entry = entry.getNext();<br>           &#125;<br>           <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>     &#125;<br><br>     <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * 从map中删除该key的值</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@param</span> key</span><br><span class="hljs-comment">      */</span><br>     <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">remove</span><span class="hljs-params">(Object key)</span> &#123;<br>           <span class="hljs-keyword">if</span>(key == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span>;<br>           <span class="hljs-type">int</span> <span class="hljs-variable">index</span> <span class="hljs-operator">=</span> index(key);<br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">pre</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">entry</span> <span class="hljs-operator">=</span> table[index];<br>           <span class="hljs-keyword">while</span>(entry != <span class="hljs-literal">null</span>) &#123;<span class="hljs-comment">//3,2,1</span><br>                 <span class="hljs-keyword">if</span> (entry.getKey().hashCode() == key.hashCode() &amp;&amp; (entry.getKey() == key || entry.getKey().equals(key))) &#123;<br>                      <span class="hljs-keyword">if</span>(pre == <span class="hljs-literal">null</span>) table[index] = entry.getNext();<br>                      <span class="hljs-keyword">else</span> pre.setNext(entry.getNext());<br>                      size--;<br>                      <span class="hljs-keyword">return</span>;<br>                 &#125;<br>                 pre = entry;<br>                 entry = entry.getNext();<br>           &#125;<br>     &#125;<br><br>     <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * 判断key是否存在于map中</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@param</span> key</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">      */</span><br>     <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">containsKey</span><span class="hljs-params">(Object key)</span> &#123;<br>           <span class="hljs-keyword">if</span>(key == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>           <span class="hljs-keyword">return</span> getEntry(key) != <span class="hljs-literal">null</span>;<br>     &#125;<br><br>     <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * 获取元素个数</span><br><span class="hljs-comment">      * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">      */</span><br>     <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">size</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.size;<br>    &#125;<br><br>     <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * 清空</span><br><span class="hljs-comment">      */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">clear</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; table.length; i++) &#123;<br>            table[i] = <span class="hljs-literal">null</span>;<br>        &#125;<br>        <span class="hljs-built_in">this</span>.size = <span class="hljs-number">0</span>;<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 获取map中的所有key</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> Object[] getAllKey() &#123;<br>     <span class="hljs-type">int</span> <span class="hljs-variable">k</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>     Object[] objects = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Object</span>[size];<br>     <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; table.length; i++) &#123;<br>           <span class="hljs-type">HashEntry</span> <span class="hljs-variable">entry</span> <span class="hljs-operator">=</span> table[i];<br>           <span class="hljs-keyword">while</span>(entry != <span class="hljs-literal">null</span>)&#123;<br>                objects[k++] = entry.getKey();<br>                entry = entry.getNext();<br>           &#125;<br>     &#125;<br>     <span class="hljs-keyword">return</span> objects;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">toString</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-type">StringBuilder</span> <span class="hljs-variable">sb</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringBuilder</span>();<br>        sb.append(String.format(<span class="hljs-string">&quot;size:%s capacity:%s resize:%s\n\n&quot;</span>, size, table.length, resize));<br>        <span class="hljs-keyword">for</span> (HashEntry entry : table) &#123;<br>            <span class="hljs-keyword">while</span> (entry != <span class="hljs-literal">null</span>) &#123;<br>                sb.append(entry.getKey() + <span class="hljs-string">&quot;:&quot;</span> + entry.getValue() + <span class="hljs-string">&quot;\n&quot;</span>);<br>                entry = entry.getNext();<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> sb.toString();<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">HashEntry</span> &#123;<br>     <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Object key;<br>     <span class="hljs-keyword">private</span> Object value;<br>     <span class="hljs-keyword">private</span> HashEntry next;<br><br>     <span class="hljs-keyword">public</span> <span class="hljs-title function_">HashEntry</span><span class="hljs-params">(Object key, Object value, HashEntry next)</span> &#123;<br>           <span class="hljs-built_in">this</span>.key = key;<br>           <span class="hljs-built_in">this</span>.value = value;<br>           <span class="hljs-built_in">this</span>.next = next;<br>     &#125;<br><br>     <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">getValue</span><span class="hljs-params">()</span> &#123;<br>           <span class="hljs-keyword">return</span> value;<br>     &#125;<br><br>     <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setValue</span><span class="hljs-params">(Object value)</span> &#123;<br>           <span class="hljs-built_in">this</span>.value = value;<br>     &#125;<br><br>     <span class="hljs-keyword">public</span> HashEntry <span class="hljs-title function_">getNext</span><span class="hljs-params">()</span> &#123;<br>           <span class="hljs-keyword">return</span> next;<br>     &#125;<br><br>     <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setNext</span><span class="hljs-params">(HashEntry next)</span> &#123;<br>           <span class="hljs-built_in">this</span>.next = next;<br>     &#125;<br><br>     <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">getKey</span><span class="hljs-params">()</span> &#123;<br>           <span class="hljs-keyword">return</span> key;<br>     &#125;<br>&#125;<br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/java/" class="category-chain-item">java</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/java/">#java</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>HashMap源码分析（基于jdk7）</div>
      <div>http://example.com/2023/06/11/HashMap源码分析（基于jdk7）/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>c5p1ng</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年6月11日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/06/11/ArrayList%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" title="ArrayList源码分析">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">ArrayList源码分析</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/06/11/LinkedList%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" title="LinkedList源码分析">
                        <span class="hidden-mobile">LinkedList源码分析</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
